package cn.zzm.acknowledge;

import cn.zzm.common.Constants;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @program: study
 * @description:消费端确认机制
 * @author: 周昭名
 * @create: 2019-04-07 22:11
 **/
public class JmsAckComsumer {

    public static void main(String[] args) {
        /*连接工厂*/
        ConnectionFactory connectionFactory;
        /*连接*/
        Connection connection = null;
        /*会话*/
        Session session = null;
        /*目的地*/
        Destination destination;
        /*消费者*/
        MessageConsumer messageConsumer;

        /*实例化连接工厂*/
        connectionFactory = new ActiveMQConnectionFactory(Constants.USERNAME, Constants.PASSWORD, Constants.BROKEURL);
        try {
            /*通过工厂获取连接*/
            connection = connectionFactory.createConnection();
            connection.start();
            /* 创建session
             * 第一个参数表示是否使用事务，第二次参数表示是否自动确认*/
            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            /*创建一个queue*/
            destination = session.createQueue("ackQueue");
            /*创建消息发送者*/
            messageConsumer = session.createConsumer(destination);

            Message message;
            while ((message = messageConsumer.receive())!=null) {
                System.out.println(((TextMessage)message).getText());
                message.acknowledge();
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}

